package com.seecen.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.pojo.entity.Company;
import com.seecen.pojo.entity.User;
import com.seecen.pojo.vo.CompanyVO;
import com.seecen.service.CompanyService;
import com.seecen.mapper.CompanyMapper;
import com.seecen.utils.Result;
import com.seecen.utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【hm_company(公司信息表)】的数据库操作Service实现
* @createDate 2025-10-16 14:51:03
*/
@Slf4j
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company>
    implements CompanyService{

    @Autowired
    private CompanyMapper companyMapper;

    @Override
    public Result selectByCompanyName(String companyName) {
        LambdaQueryWrapper<Company> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Company::getCompanyId,Company::getCompanyName)
                .like(Company::getCompanyName,companyName);
        List<Company> companys = companyMapper.selectList(wrapper);
        if(ObjectUtil.isEmpty(companys)){
            return Result.build(null, ResultCode.COMPANY_NOT_FOUND);
        }

        //Company转换为CompanyVO
        List<CompanyVO> companyVOs = companys.stream()
                .map(company -> {
                    CompanyVO vo = new CompanyVO();
                    BeanUtils.copyProperties(company, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        HashMap map = new HashMap<>();
        map.put("company",companyVOs);
        return Result.ok(map);
    }

    @Override
    public Result selectHotCompanyList() {
        LambdaQueryWrapper<Company> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Company::getComplaintCount)
                .last("LIMIT 8");

        List<Company> companys = companyMapper.selectList(wrapper);
        if(ObjectUtil.isEmpty(companys)){
            return Result.build(null, ResultCode.COMPANY_NOT_FOUND);
        }

        //Company转换为CompanyVO
        List<CompanyVO> companyVOs = companys.stream()
                .map(company -> {
                    CompanyVO vo = new CompanyVO();
                    BeanUtils.copyProperties(company, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        HashMap map = new HashMap<>();
        map.put("company",companyVOs);
        return Result.ok(map);
    }

    //红黑榜查询公司名称和图片，并区分红黑榜
    @Override
    public Result getRankingData(Integer tid) {
        if (tid == null || tid <= 0) {
            return Result.build(null, ResultCode.COMPANY_NOT_FOUND);
        }
        log.info("获取分类 {} 的红黑榜数据", tid);
        LambdaQueryWrapper<Company> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Company::getTid, tid)
                .eq(Company::getIsDeleted, 0)
                .select(Company::getCompanyId,
                        Company::getCompanyName,
                        Company::getCompanyPicture,
                        Company::getComplaintCount,
                        Company::getResolvedComplaintCount);

        List<Company> companies = companyMapper.selectList(wrapper);
        if (companies.isEmpty()) {
            return Result.build(null, ResultCode.COMPANY_NOT_FOUND);
        }
        // 准备红榜、黑榜数据
        List<Map<String, Object>> redList = new ArrayList<>();
        List<Map<String, Object>> blackList = new ArrayList<>();
        // 分类
        for (Company company : companies) {
            Integer companyId = company.getCompanyId();
            String name = company.getCompanyName();
            String logo = company.getCompanyPicture();
            Integer complaintCount = company.getComplaintCount() != null ? company.getComplaintCount() : 0;
            Integer resolvedCount = company.getResolvedComplaintCount() != null ? company.getResolvedComplaintCount() : 0;

            int unresolvedCount = complaintCount - resolvedCount;

            Map<String, Object> item = Map.of(
                    "id",companyId,
                    "name", name,
                    "logo", logo
            );

            if (unresolvedCount <= 0) {
                // 红榜：全部投诉已解决
                redList.add(item);
            } else {
                // 黑榜：还有未解决投诉
                blackList.add(item);
            }
        }

//        //  红榜：按投诉总数升序（投诉少的在前）
//        redList.sort((a, b) -> Integer.compare(
//                (Integer) ((Map) a).get("complaintCount") != null ? (Integer) ((Map) a).get("complaintCount") : 0,
//                (Integer) ((Map) b).get("complaintCount") != null ? (Integer) ((Map) b).get("complaintCount") : 0
//        ));

        //  黑榜：按投诉总数降序（投诉多的在前）
        blackList.sort((a, b) -> Integer.compare(
                (Integer) ((Map) b).get("complaintCount") != null ? (Integer) ((Map) b).get("complaintCount") : 0,
                (Integer) ((Map) a).get("complaintCount") != null ? (Integer) ((Map) a).get("complaintCount") : 0
        ));

        // 限制每榜最多显示 5 个
        int limit = 5;
        Map<String, Object> data = new HashMap<>();
        data.put("red", redList.stream().limit(limit).collect(Collectors.toList()));
        data.put("black", blackList.stream().limit(limit).collect(Collectors.toList()));
        data.put("efficiency", new ArrayList<>()); // 暂空，后续可扩展

        return Result.ok(data);
    }

    @Override
    public Result InsertComplaintsCountByName(String companyName) {
        LambdaQueryWrapper<Company> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Company::getCompanyName,companyName);
        Company company = companyMapper.selectOne(wrapper);
        if(ObjectUtil.isEmpty(company)){
            return Result.build(null, ResultCode.COMPANY_NOT_FOUND);
        }
        company.setComplaintCount(company.getComplaintCount() + 1);
        company.setUpdateTime(new Date());
        int i = companyMapper.updateById(company);
        if (i != 1) {
            return Result.build(null, ResultCode.SUBMISSION_FAILED);
        }
        return Result.ok("提交成功");
    }


}




